package by.grsu.dz.page.sample;

import java.util.List;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;

import by.grsu.dz.app.MyFirstWebApplication;
import by.grsu.dz.dao.impl.CircleDao;
import by.grsu.dz.entity.Circle;

/**
 * Page displays list of "Circle" objects.
 * 
 * @author dmitry_zhivushko
 * @since Nov 2, 2014
 */
public class CirclesListPage extends WebPage {

	public CirclesListPage() {
		super();

		// retrieve new instance of DAO (can be reused)
		final CircleDao circleDao = new CircleDao(MyFirstWebApplication.DATA_XML_FOLDER);

		// get list of Circle objects using DAO
		final List<Circle> allCircles = circleDao.getAll();

		// create "repeater" component to build rows of the "table" in output HTML
		add(new DataView<Circle>("table-rows", new ListDataProvider<Circle>(allCircles)) {
			@Override
			protected void populateItem(final Item<Circle> item) {
				final Circle circle = item.getModelObject();
				// add data for table cell in row
				item.add(new Label("id", circle.getId()));
				item.add(new Label("color", circle.getColor()));
				item.add(new Label("radius", circle.getRadius()));

				// add button component to open "edit" page
				item.add(new Link("editLink") {
					@Override
					public void onClick() {
						// open "edit" page for specified Circle
						setResponsePage(new CircleEditPage(circle));
					}
				});

				// add button component to delete Circle
				item.add(new Link("deleteLink") {
					@Override
					public void onClick() {
						// execute "delete" operation
						circleDao.delete(circle.getId());
						// reload page
						setResponsePage(new CirclesListPage());
					}
				});
			}
		});

		// add button component to open "edit" page
		add(new Link("createLink") {
			@Override
			public void onClick() {
				// open "edit" page for NEW Circle
				setResponsePage(new CircleEditPage(new Circle()));
			}
		});
	}
}
